package sw6.visualschedule.adminpanel;

import sw6.visualschedule.R;
import sw6.visualschedule.entities.DbDate;
import sw6.visualschedule.entities.ScheduleActivity;
import sw6.visualschedule.extendedViews.DateTimePickerDialog;
import sw6.visualschedule.extendedViews.DateTimePickerDialog.OnDateTimeSetListener;
import sw6.visualschedule.persistence.DateRepo;
import sw6.visualschedule.persistence.ScheduleActivityRepo;
import tools.BundleHelper;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TimePicker;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

public class ActivityDateList extends ListActivity {

	private final static int ADDDATEDIALOG = 1;
	private final static int EDITDATEDIALOG = 2;
	
    private transient DbDate dbDateBeingEdited;
    
    private transient ScheduleActivity mActivity;

    final transient private OnDateTimeSetListener mActivityDateAddedDateTimeSetListener = new OnDateTimeSetListener() {
		@Override
		public void onDateTimeSet(final DatePicker datePickerView, final TimePicker timePickerView, final int year, final int monthOfYear, final int dayOfMonth, final int hourOfDay, final int minute) {
			final GregorianCalendar cal = new GregorianCalendar();
			cal.set(year, monthOfYear, dayOfMonth, hourOfDay, minute);			
			final Date date = cal.getTime();
						
			Toast.makeText(ActivityDateList.this, "Added " + date.toLocaleString(), Toast.LENGTH_LONG).show();
			
			final DbDate dbDate = new DbDate(mActivity, date);
			mDateService.create(dbDate);
			
			populateList();
		}
    };
    final transient private OnDateTimeSetListener mActivityDateModifiedDateTimeSetListener = new OnDateTimeSetListener() {
		@Override
		public void onDateTimeSet(final DatePicker datePickerView, final TimePicker timePickerView, final int year, final int monthOfYear, final int dayOfMonth, final int hourOfDay, final int minute) {
			final GregorianCalendar cal = new GregorianCalendar();
			cal.set(year, monthOfYear, dayOfMonth, hourOfDay, minute);			
			final Date date = cal.getTime();
			
			Toast.makeText(ActivityDateList.this, "Date was changed to " + date.toLocaleString(), Toast.LENGTH_LONG).show();
			
			dbDateBeingEdited.setDate(date);
			mDateService.update(dbDateBeingEdited);
			
			//dbDateBeingEdited = null;
			
			populateList();
		}
    };
    
    private transient ScheduleActivityRepo mActivityService;
    private transient int mCurrentActivityId = -1;
    
    private transient List<DbDate> mDates;

    private transient DateRepo mDateService;
    
    @Override
    public void onCreate(final Bundle bundle) {
        super.onCreate(bundle);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    
        mCurrentActivityId = getIntent().getIntExtra(BundleHelper.ACTIVITY_ID, -1);
        
        mDateService = new DateRepo(this);
        mActivityService = new ScheduleActivityRepo(this);
        
        final ListView list = getListView();
        list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(final AdapterView<?> adapter, final View view, final int pos, final long itemId) {
                return onLongListItemClick(view, pos, itemId);
            }
        });
    }
    
    /**
     * @see super
     */
    @Override
	public boolean onCreateOptionsMenu(final Menu menu) {
	    final MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.dates_pref, menu);
	    return true;
	}
        
    /**
     * @see super
     */
	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {
	    boolean result = false;
	    
	    if (item.getItemId() == R.id.add_date) {
	    	//Show dialog and create date
	    	showDialog(ADDDATEDIALOG);
	        result = true;
	    } else {
	        result = super.onOptionsItemSelected(item);
	    }
	    
	    return result;
	}
    
    private void deleteDate(final DbDate dbDate) {
        mDateService.delete(dbDate);
        
        Toast.makeText(this, "Deleted " + dbDate, Toast.LENGTH_SHORT).show();
        
        populateList();
    }
    
    private void populateList() {
        mDates = new ArrayList<DbDate>(mDateService.getActivityDates(mCurrentActivityId));
        
        final ArrayAdapter<DbDate> adapter = new ArrayAdapter<DbDate>(this, android.R.layout.simple_list_item_1, mDates);             
        setListAdapter(adapter);
    }
	
    @Override
	protected Dialog onCreateDialog(final int itemId) {
	    DateTimePickerDialog result = null;
	    
		if (itemId == 1) {	    	
	    	final Date date = new Date();
	    	result = new DateTimePickerDialog(this, mActivityDateAddedDateTimeSetListener , date, true);
	    } else if (itemId == 2) {
	    	final Date date = dbDateBeingEdited.getDate();
	    	result = new DateTimePickerDialog(this, mActivityDateModifiedDateTimeSetListener , date, true);
	    }
	    
	    return result;
	}
	
	@Override
    protected void onListItemClick(final ListView list, final View view, final int position, final long itemId) {
    	super.onListItemClick(list, view, position, itemId);
    	
    	dbDateBeingEdited = mDateService.getById(mDates.get(position).getId());
    	
    	showDialog(EDITDATEDIALOG);
    }
	
    protected boolean onLongListItemClick(final View view, final int pos, final long itemId) {
    	final DbDate dbDate = mDateService.getById(mDates.get(pos).getId());		
		
		new AlertDialog.Builder(this)
		.setTitle(R.string.dd_delete_date)
		.setMessage(getString(R.string.dd_do_you_want_to_delete, dbDate.getDate().toLocaleString()))
		.setIcon(android.R.drawable.ic_dialog_alert)
		.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
		    public void onClick(final DialogInterface dialog, final int whichButton) {
		        //User clicked yes
		    	deleteDate(dbDate);
		    }
		 })
		 .setNegativeButton(android.R.string.no, null).show();

	    return true;
	}
    
    @Override
    protected void onResume() {
        super.onResume();
        
        mActivity = mActivityService.getById(mCurrentActivityId);
        setTitle(getString(R.string.adm_activitydates_title, mActivity.getTitle()));
        
        populateList();
        
        Toast.makeText(this, getString(R.string.dateslist_info), Toast.LENGTH_LONG).show();
    }
    
}